package com.winai.launcher.view.set;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.BroadcastReceiver.SystemEventReceiver;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.MainRouter;
import com.winai.launcher.manager.DeviceInfoManager;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.AppExecutors;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.utils.OpenAppUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/11/15 0015
 * 描述：设置中心
 */
@SuppressLint("SetTextI18n")
public class SetActivity extends BaseActivity {
    private Context mContext = this;
    private final int RESULT_CODE = 10000;//小艾音箱 退出登录 的回调

    @BindView(R.id.tv_wifi)
    TextView tvWifi;
    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.tv_bluetooth)
    TextView tvBluetooth;
    @BindView(R.id.tv_my)
    TextView tvMy;

    private int voiceNum = 0;//当前音量
    private AudioManager mAudioManager;
    private ContentObserver volMode;//监听音量
    private boolean consume = true;//消耗参数，避免重复跳转激活页面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initView();
        initListener();
        registerReceivers();
    }

    private void registerReceivers() {
        volMode = new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                initObject();
            }
        };

        mContext.getContentResolver().registerContentObserver(
                android.provider.Settings.System.CONTENT_URI
                , true
                , volMode);
    }

    private void initObject() {
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (mAudioManager != null) {
            /*得到比例转换值，然后展示出来*/
            int currentVolume = SystemEventReceiver.mIndex;
            if (currentVolume == 0) {
                currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            }
            if (currentVolume > 0) {
                ivVoice.setImageResource(R.mipmap.icon_set_voice_on);
            } else {
                ivVoice.setImageResource(R.mipmap.icon_set_voice_off);
            }
        }
    }

    private void initView() {
        changeBluetoothText(Constant.bluetoothLinked);//蓝牙-已连接
    }

    /**
     * 说明：渲染WiFi文字
     */
    private void initWifiText(boolean linked) {
        if (linked) {
            tvWifi.setText("已连接");
            tvWifi.setBackground(getResources().getDrawable(R.drawable.bg_btn_green_100dp));
        } else {
            tvWifi.setText("未连接");
            tvWifi.setBackground(getResources().getDrawable(R.drawable.bg_btn_888_100dp));
        }
    }

    /**
     * 说明：渲染蓝牙文字
     */
    private void changeBluetoothText(boolean linked) {
        if (linked) {
            tvBluetooth.setText("已连接");
            tvBluetooth.setBackground(getResources().getDrawable(R.drawable.bg_btn_green_100dp));
        } else {
            tvBluetooth.setText("未连接");
            tvBluetooth.setBackground(getResources().getDrawable(R.drawable.bg_btn_888_100dp));
        }
    }

    /**
     * 说明：渲染个人中心文字
     */
    private void initLoginText(boolean login) {
        if (login) {
            tvMy.setText("已登录");
            tvMy.setBackground(getResources().getDrawable(R.drawable.bg_btn_green_100dp));
        } else {
            tvMy.setText("未登录");
            tvMy.setBackground(getResources().getDrawable(R.drawable.bg_btn_888_100dp));
        }
    }

    private void initListener() {
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.CHANGE_WIFI:
                        initWifiText(NetworkUtils.hasNetwork(mContext));//WiFi-已连接
                        break;
                    case GlobalPublisher.CHANGE_VOICE:
                        voiceNum = arg1;
                        //设置音量跟随改变
                        initObject();
                        break;
                    case GlobalPublisher.REMOVE_BOND_BLUETOOTH:
                    case GlobalPublisher.BLUETOOTH_DEVICE_DISCONNECTED:
                        changeBluetoothText(false);
                        break;
                    case GlobalPublisher.BOND_BLUETOOTH:
                        changeBluetoothText(true);
                        break;
                    case GlobalPublisher.CHANGE_VOICE_RECEIVER:
                        //接收到系统音量改变
                        initObject();
                        break;
                    case GlobalPublisher.LOGOUT:
                        initLoginText(false);
                        if (consume) {
                            consume = false;
                            /* 跳转艾益生的激活app */
                            LogUtils.e("跳转艾益生的激活app");
                            try {
                                Intent intent = new Intent();
                                intent.setClassName("com.aiyisheng.speaker"
                                        , "com.aiyisheng.speaker.user.activation.ActivationActivity");
                                intent.putExtra("deviceId", BaseUtils.getDeviceId());//新增deviceId参数
                                startActivityForResult(intent, RESULT_CODE);
                                /*((BaseActivity) mContext).overridePendingTransition(0, 0);*/
                            } catch (Exception e) {
                                e.printStackTrace();
                                ToastKs.show(mContext, "您还没有安装小艾音箱");
                            }
                        }
                        break;
                }
            }
        });
    }

    /**
     * 说明：获取系统亮度
     */
    private int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.cl_search, R.id.cl_wifi, R.id.cl_voice, R.id.cl_light, R.id.cl_bluetooth
            , R.id.cl_my, R.id.cl_showFunc, R.id.cl_feedback, R.id.cl_about, R.id.cl_reset, R.id.cl_myDevice})
    public void onViewClicked(View view) {
        Map<String, Object> map = new HashMap<>();
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.cl_search:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_FORUM_SEARCH, ".搜索@");
                break;
            case R.id.cl_wifi:
                Intent setWifiIntent = new Intent(mContext, SetWifiActivity.class);
                setWifiIntent.putExtra("titleName", "无线网络");
                startActivity(setWifiIntent);
//                map.put("titleName", "无线网络");
//                startAct(mContext, SetWifiActivity.class, map);
                break;
            case R.id.cl_voice:
                Intent setVoiceIntent = new Intent(mContext, SetVoiceActivity.class);
                setVoiceIntent.putExtra("titleName", "声音设置");
                startActivity(setVoiceIntent);
//                map.put("titleName", "声音设置");
//                startAct(mContext, SetVoiceActivity.class, map);
                break;
            case R.id.cl_light:
                Intent setLightIntent = new Intent(mContext, SetLightActivity.class);
                setLightIntent.putExtra("titleName", "屏幕设置");
                startActivity(setLightIntent);
//                map.put("titleName", "屏幕设置");
//                startAct(mContext, SetLightActivity.class, map);
                break;
            case R.id.cl_bluetooth:
                Intent setBluetoothIntent = new Intent(mContext, SetBluetoothNewActivity.class);
                setBluetoothIntent.putExtra("titleName", "蓝牙设置");
                startActivity(setBluetoothIntent);
//                map.put("titleName", "蓝牙设置");
//                startAct(mContext, SetBluetoothActivity.class, map);
                break;
            case R.id.cl_my:
                if (isWifiConnect()) {
                    OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_USER_CENTER, ".个人中心@");
                } else {
                    ToastKs.show(mContext, "请先连接网络");
                }
                break;
            case R.id.cl_showFunc:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_AUDIO_FUNCTION, ".功能演示@");
                break;
            case R.id.cl_feedback:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_USER_HELPER, ".帮助反馈@");
                break;
            case R.id.cl_about:
                Intent setAboutUsIntent = new Intent(mContext, SetAboutUsActivity.class);
                setAboutUsIntent.putExtra("titleName", "关于设备");
                startActivity(setAboutUsIntent);
//                map.put("titleName", "关于设备");
//                startAct(mContext, SetAboutUsActivity.class, map);
                break;
            case R.id.cl_reset:
                Intent setResetIntent = new Intent(mContext, SetResetDeviceActivity.class);
                setResetIntent.putExtra("titleName", "恢复出厂设置");
                startActivity(setResetIntent);
//                map.put("titleName", "恢复出厂设置");
//                startAct(mContext, SetResetDeviceActivity.class, map);
                break;
            case R.id.cl_myDevice:
                //我的设备
                Intent myDevice = new Intent(mContext, AysDeviceActivity.class);
                startActivity(myDevice);
                break;
        }
    }

    /**
     * 检查wifi是否处开连接状态
     *
     * @return
     */
    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifiInfo.isConnected();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initWifiText(isWifiConnect());//WiFi-已连接
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mContext.getContentResolver().unregisterContentObserver(volMode);
    }

    /**
     * 说明：获取系统等声音
     */
    private void getVolume() {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (am == null) {
            LogUtils.e("没有找到Audio_service服务");
            return;
        }
        int max = am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);// 0
        int current = am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
        Log.e("service", "通话音量值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 1
        current = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        Log.e("service", "系统音量值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_RING);// 2
        current = am.getStreamVolume(AudioManager.STREAM_RING);
        Log.e("service", "系统铃声值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);// 3
        current = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        Log.e("service", "音乐音量值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_ALARM);// 4
        current = am.getStreamVolume(AudioManager.STREAM_ALARM);
        Log.e("service", "闹铃音量值：" + max + "-" + current);

        max = am.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);// 5
        current = am
                .getStreamVolume(AudioManager.STREAM_NOTIFICATION);
        Log.e("service", "提示声音音量值：" + max + "-" + current);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RESULT_CODE:
                    if (data != null) {
                        long userId = data.getLongExtra("userId", 0);
                        initLoginText(true);
                        AppExecutors.getInstance().networkIO().execute(new Runnable() {
                            @Override
                            public void run() {
                                // 更新设备最近绑定状态
                                DeviceInfoManager.getInstance(mContext).updateBind(
                                        BaseUtils.timeStamp2Date(BaseUtils.getInitTime(), "")
                                        , String.valueOf(userId)
                                );
                            }
                        });
                        //说明：禁止或允许下拉状态栏
                        NotifyReceiverUtils.notifyPulldownReceiver(mContext.getApplicationContext(), true);
                        NotifyReceiverUtils.notifyAiyishengLogin(mContext.getApplicationContext());//通知ai，艾益生登陆成功
                        NotifyReceiverUtils.notifyToggleWakeUpReceiver(mContext.getApplicationContext(), true);
                        //模拟HOME
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        mContext.startActivity(intent);
                    }
                    break;
            }
        }
    }
}
